<?php

namespace App\Http\Controllers;

use App\Models\User;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return array
     * @author lzx
     * @time 2021/6/17 0:33
     */
    public function login(Request $request): array
    {
        $user = User::where([
            ['name', '=', $request->account], ['password', '=', md5($request->password)]
        ])->orWhere([
            ['email', '=', $request->account], ['password', '=', md5($request->password)]
        ])->first();

        if (!$user) {
            return outPut([], 202, '登录信息有误');
        }
        $payload = [$user->email, $user->password];
        if ($request->remember) {
            $payload[] = time() + 30 * 86400;
            $payload[] = $user->remember_token;
        } else {
            $payload[] = time() + 30 * 60;
        }
        $user->account = $user->name;
        $user->token = JWT::encode($payload, md5('kite'));
        $user->failure_time = $payload[2];
        unset($user->password, $user->remember_token);
        return outPut($user->toArray(), 0);
    }
}
